<template>
  <el-dialog
    v-model="dialogVisible"
    :before-close="closeDialog"
    :show-close='false'
    :close-on-click-modal="false"
    append-to-body
    :width="isRadio ? '445px' : '730px'"
    class="custom-dialog user-info-list-dialog"
    modal-class="dialog-center"
  >
    <div class="custom-dialog-header">
      <div class="title-box">
          <div class="title">{{dialogTitle}}</div>
      </div>
      <svg class="close-icon" @click="closeDialog">
          <use xlink:href="#keowledge-danchuangguanbi1"></use>
      </svg>
    </div>
    <div class="user-info-list" v-if="dialogVisible">
      <div class="user-info-left">
        <div class="user-info-title">
          <template v-for="(item,index) in tabList">
            <div  :key="index" class="user-tab-item" :class="[activeName==item.value && 'user-tab-active']" v-if="showItem(item)"
             @click="changeActive(item)">
              {{$t(item.label)}}
            </div>
          </template>
        </div>
        <div class="user-info-body" v-loading="userLoading || publicLoading">
          <div class="search-box">
            <svg class="icon">
              <use xlink:href="#keowledge-sousuo"></use>
            </svg>
            <div data-v-98dd7c30="" class="h-line"></div>
            <el-input class="text" v-model="keyword" @input="hanldeSearch" :placeholder="$t('message.placeholder.pleasePhoneOrName')"></el-input>
            <svg class="close-icon" v-show="!!keyword" @click="clearKeyWord">
              <use xlink:href="#keowledge-danchuangguanbi"></use>
            </svg>
          </div>
          <div class="content" :class="[activeName!='user'&&'no-user-content']">
            <el-scrollbar ref="checkUserScroll">
              <div class="check-box-item" v-for="(item,index) in getCurrentList" @click="addUser(item,index)" :key="index" v-show="activeName!='dept'">
                <svg class="icon" v-if="!isRadio">
                  <use v-bind:xlink:href="`#${checkListId.includes(item.userId||item.id)?'keowledge-a-zu3739':'keowledge-a-juxing2862biankuang'}`"></use>
                </svg>
                <svg class="icon" v-else>
                  <use v-bind:xlink:href="`#${checkListId.includes(item.userId||item.id)?'keowledge-a-yuanxing5biankuang':'keowledge-a-zu3772'}`"></use>
                </svg>
                <img :src="item.headImg" v-if="activeName=='user'">
                <span class="name">{{getCurrentName(item)}}</span>
              </div>
              <el-tree v-if="activeName=='dept'" node-key="id"
                :data="getCurrentList"
                @node-click="handleDeptNodeClick"
                :props="defaultProps">
                <template #default="{ node, data }">
                  <div class="custom-tree-node">
                    <div class="check-box">
                      <svg class="icon" v-if="!isRadio">
                        <use v-bind:xlink:href="`#${checkListId.includes(data.id)?'keowledge-a-zu3739':'keowledge-a-juxing2862biankuang'}`"></use>
                      </svg>
                      <svg class="icon" v-else>
                        <use v-bind:xlink:href="`#${checkListId.includes(data.id)?'keowledge-a-yuanxing5biankuang':'keowledge-a-zu3772'}`"></use>
                      </svg>
                    </div>
                    <div class="tree-labe">
                      {{node.label}}
                    </div>
                  </div>
                </template>
              </el-tree>
            </el-scrollbar>
          </div>
          <div  class="page" v-if="activeName=='user'">
            <svg class="icon" @click="cutPage('label')">
                <use xlink:href="#keowledge-a-zu4701-copy"></use>
            </svg>
            <el-input-number v-model="page.current" :min="1" :max="Math.ceil(page.total/page.size) || 1" 
                controls-position="right" @blur="numberBlur('label')" @keyup.enter="numberBlur('label')"></el-input-number>
            <span class="split">/</span>
            <span>{{Math.ceil(page.total/page.size)}}</span>
            <svg class="icon" @click="addPage('label')">
                <use xlink:href="#keowledge-a-zu4701"></use>
            </svg>
          </div>
        </div>
      </div>
      <div class="user-info-right" v-if="!isRadio">
        <div class="user-right-title">
          <div class="num">{{$t('message.text.checked')}}({{checkList.length}})</div>
          <div class="clear" @click="handleClear">{{$t('message.clear')}}</div>
        </div>
        <div class="user-right-content">
          <el-scrollbar ref="checkScroll">
            <div v-for="(item,index) in checkList" class="cehck-item" :key="index">
              <div class="check-item-info">
                <img v-if="item.headImg" :src="item.headImg">
                <span :title="`${item.typeName ? '（' + item.typeName + '）' + item.name : item.name}`">{{item.typeName ? '（' + item.typeName + '）' + item.name : item.name}}</span>
              </div>
              <svg class="close-icon" @click="delCheck(item, index)">
                <use xlink:href="#keowledge-danchuangguanbi"></use>
              </svg>
            </div>
          </el-scrollbar>
        </div>
      </div>
    </div>
    <template #footer>
      <div class="custom-dialog-footer">
        <el-button size="mini" @click="cancel">{{$t('message.buttons.cancal')}}</el-button>
        <el-button size="mini" type="primary" @click="submit" :disabled="submitLoading">{{$t('message.buttons.submit')}}</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {
  ref,
  reactive,
  toRefs,
  watch ,
  onMounted,
  getCurrentInstance,nextTick, computed
} from 'vue' 
import { useHookI18n } from '@/hooks/i18n'
const { locale,$t } = useHookI18n()
import { useRouter } from "vue-router"
import {getUserListAll,getSelectedUsers , getUserListPage, getUserTreeType} from "@/api/common";
const router = useRouter();

const emit = defineEmits(["cancel",'submit'])
const props = defineProps({
  // 是否可选岗位
  jobEnable: {
    type: Boolean,
    default: () => {
      return false
    }
  },
  // 是否可选人员
  userEnable: {
    type: Boolean,
    default: () => {
      return false
    }
  },
  // 是否可选角色
  roleEnable: {
    type: Boolean,
    default: () => {
      return false
    }
  },
  // 是否可选部门
  deptEnable: {
    type: Boolean,
    default: () => {
      return false
    }
  },
  // 是否可选群组
  groupEnable: {
    type: Boolean,
    default: () => {
      return false
    }
  },
  selectable: {
    type: Boolean,
    default: () => {
      return false
    }
  },
  // 是否是单选
  isRadio: {
    type: Boolean,
    default: () => {
      return false
    }
  },
  // 当前选中tab
  currentActiveName: {
    type: String,
    default: () => {
      return 'user'
    }
  },
  // 弹框标题
  dialogTitle: {
    type: String,
    default: () => {
      return '人员选择'
    }
  }
})
const dialogVisible = ref(false)
const submitLoading = ref(false)
const userLoading = ref(false)
const publicLoading = ref(false)
const isSingleTab = ref(false)
const activeName = ref('')
const userList = ref([])
const roleList = ref([])
const jobList = ref([])
const groupList = ref([])
const deptList = ref([])
const checkData = ref([])
const checkList = ref([])
const checkListId = ref([])
const userOptionList = ref([])
const keyword = ref('')
const checkScroll = ref()
const page = ref({
  size: 30,
  current: 1,
  total:0,
  backPage:1
})
const tabList = ref([{
  label:'message.typeMenu.member',
  value:'user',
  authKey:'userEnable'
},{
  label:'message.typeMenu.role',
  value:'role',
  authKey:'roleEnable'
},{
  label:'message.typeMenu.dept',
  value:'dept',
  authKey:'deptEnable'
},{
  label:'message.typeMenu.job',
  value:'job',
  authKey:'jobEnable'
},{
  label:'message.typeMenu.group',
  value:'group',
  authKey:'groupEnable'
}])
const defaultProps = {
  children: 'childList',
  label: 'name',
}
const checkUserScroll = ref()
const getCurrentList = computed(()=>{
  switch (activeName.value) {
    case 'user':
      return userList.value
      break;
    case 'role':
      return roleList.value
      break
    case 'dept':
      return deptList.value
      break
    case 'job':
      return jobList.value
      break
    default:
      return groupList.value
      break;
  }
})
async function openDialog(arr){
  if(dialogVisible.value) return
  submitLoading.value = true
  const flagArr = [props.jobEnable, props.userEnable, props.roleEnable, props.deptEnable, props.groupEnable]
  let flagCount = 0
  flagArr.forEach(item => {
    if (item) {
      flagCount ++
    }
  })
  isSingleTab.value = flagCount > 1
  await getAllUser(arr)
  dialogVisible.value = true
  activeName.value = props.currentActiveName
  await getUserList()
  await getTreeData()
}
// 分页获取用户列表
function getUserList () {
  userLoading.value = true
  const params = {
    key: keyword.value,
    size: page.value.size,
    current: page.value.current
  }
  getUserListPage(params).then(res => {
    if (res.data && res.data.code == 0) {
      userList.value = res.data.data.records || []
      page.value.total = res.data.data.total
      userLoading.value = false
    } else {
      userLoading.value = false
    }
  }).catch(err => {
    userLoading.value = false
  })
}
function showItem(item){
  return props[item.authKey]
}
// 获取部门人员树
async function getTreeData () {
  publicLoading.value = true
  const params = {
    value: keyword.value,
    type: activeName.value
  }
  await getUserTreeType(params).then(res => {
    if (res.data && res.data.code == 0) {
      // userList.value = [...res.data.data.users]
      roleList.value = [...res.data.data.roles]
      jobList.value = [...res.data.data.jobs]
      groupList.value = [...res.data.data.groups]
      deptList.value = [...res.data.data.depts]
      publicLoading.value = false
    } else {
      publicLoading.value = false
    }
  }).catch(err => {
    publicLoading.value = false
  })
}
function getAllUser(arr) {
  initCheckList(arr)
}
function getCurrentName(item){
  let key = 'realName'
  switch (activeName.value) {
    case 'role':
      key = 'roleName'
      break;
    case 'job':
      key = 'name'
      break;
    case 'dept':
      // key = 'name'
      break;
    case 'group':
      key = 'name'
      break;
    default:
      break;
  }
  return item[key]
}
// 初始化已选数据
function initCheckList(arr) {
    let ids = []
    submitLoading.value = true
    arr.forEach(item => {
      if (item.type === 'user') {
        ids.push(item.userId || item.id)
      }
      if (item.type === 'role') {
        checkList.value.push({ id: item.userId || item.id, name: item.name,type:'role', typeName: '角色' })
      }
      if (item.type === 'job') {
        checkList.value.push({ id: item.userId || item.id, name: item.name,type:'job', typeName: '岗位' })
      }
      if (item.type === 'dept') {
        checkList.value.push({ id: item.userId || item.id, name: item.name,type:'dept', typeName: '部门' })
      }
      if (item.type === 'group') {
        checkList.value.push({ id: item.userId || item.id, name: item.name,type:'group', typeName: '群组' })
      }
      checkListId.value.push(item.userId || item.id)
    })
    if(ids.length>0){
      getSelectedUsers(ids).then(res=>{
        if(res.data.code == 0 ){
          res.data.data.forEach(item=>{
            checkList.value.push({
              id:item.id,
              headImg:item.headImg,
              type:'user',
              name:item.realName || item.name
            })
          })
          checkData.value = JSON.parse(JSON.stringify(checkList.value))
        }
      }).finally(res=>{
        submitLoading.value = false
      })
    }else{
      checkData.value = JSON.parse(JSON.stringify(checkList.value))
      submitLoading.value = false
    }
}
function changeActive(item){
  activeName.value = item.value
}
// 清空已选择数据
function handleClear() {
  checkList.value = []
  checkData.value = []
}
function clearKeyWord(){
  keyword.value = ''
  hanldeSearch()
}
function hanldeSearch(){
  if (activeName.value === 'user') {
    page.value.current = 1
    getUserList()
  } else {
    getTreeData()
  }
}
function addUser(node){
  let type = activeName.value
  let name = ''
  let headImg = null
  let typeName = null
  if (type === 'user') {
    name = node.realName
    headImg = node.headImg
  }
  if (type === 'role') {
    name = node.roleName
    typeName = $t('message.typeMenu.role')
  }
  if (type === 'job') {
    name = node.name
    typeName = $t('message.typeMenu.job')
  }
  if (type === 'group') {
    name = node.name
    typeName = $t('message.typeMenu.group')
  }
  const obj = { id: node.id, name: name, headImg: headImg, typeName: typeName }
  const dataObj = { id: node.id, name: name, type: type , headImg: headImg }
  const index = checkList.value.findIndex(item => {
    return item.id === node.id
  })
  if (props.isRadio) {
    checkList.value = [obj]
    checkData.value = [dataObj]
    // 新版单选也需要确定操作
    // submit()
  }
  if (index === -1) {
    checkList.value.push(obj)
    checkData.value.push(dataObj)
    checkListId.value.push(obj.id)
  } else {
    delCheck(obj,index)
  }
}
function numberBlur(){
  if( page.value.current &&  page.value.current!= page.value.backPage){
      getUserList()
  }
  if(!page.value.current){
    page.value.current = page.value.backPage
  }else{
    page.value.backPage = page.value.current
  }
}
function cutPage(){
  page.value.current -= 1
  if( page.value.current<1){
    page.value.current = 1
  }
  page.value.backPage = page.value.current
  getUserList()
}
function addPage(){
  page.value.current += 1
  if(page.value.current>Math.ceil(page.value.total/page.value.size)){
    page.value.current = Math.ceil(page.value.total/page.value.size)
  }
  page.value.backPage = page.value.current
  getUserList()
}
// 提交数据
function submit () {
  const submitArr = [...checkData.value]
  emit('submit', submitArr)
  nextTick(()=>{
    closeDialog()
  })
}
// 取消
function cancel () {
  emit('cancel', true)
  closeDialog()
}
// 删除已选成员
function delCheck (item, index) {
  checkList.value.splice(index, 1)
  checkData.value.splice(index, 1)
  checkListId.value.splice(index, 1)
  for(let i in userOptionList.value) {
    let tix = isInArr('id', userOptionList.value[i].id, checkList.value)
    if(tix == -1) {
      userOptionList.value[i].checked = false
    }
  }
}
// 判断是否已存在数组中,存在返回index
function isInArr (attr, val, list) {
  let index = -1
  for(let i in list) {
    if(list[i][attr] == val) {
      index = i
    }
  }
  return index
}
interface Tree {
  name: string
}
function handleCheckChange(data: Tree,
  checked: boolean,
  indeterminate: boolean){
  console.log(data,checked,indeterminate)
}
// 点击tree组件节点
function handleDeptNodeClick(data) {
  const obj = { id: data.id, name: data.name, typeName: $t('message.typeMenu.dept') }
  const dataObj = { id: data.id, name: data.name, type: 'dept' }
  const index = checkList.value.findIndex(item => {
    return item.id === data.id
  })
  if (props.isRadio) {
    checkList.value = [obj]
    checkData.value = [dataObj]
    // 新版单选也需要确定操作
    // submit()
  }
  if (index === -1) {
    checkList.value.push(obj)
    checkData.value.push(dataObj)
    checkListId.value.push(obj.id)
  } else {
    delCheck(obj,index)
  }
}
// 关闭弹窗
function closeDialog () {
  dialogVisible.value = false
  keyword.value = ""
  userOptionList.value = []
  checkList.value = []
  checkData.value = []
  roleList.value = []
  jobList.value = []
  groupList.value = []
  deptList.value = []
  userList.value = []
  checkListId.value = []
}
defineExpose({
  openDialog
})
</script>
<style lang="scss">
.user-info-list{
  display: flex;
  .user-info-left{
    width: 460px;
    border-right: 1px solid #EEEFF0;
    .user-info-title{
      display: flex;
      align-items: center;
      height: 40px;
      padding: 0px 32px;
      border-bottom: 1px solid #eeeff0;
      .user-tab-item{
        height: 40px;
        font-size: 14px;
        color: #6f7588;
        cursor: pointer;
        position: relative;
        display: flex;
        align-items: center;
      }
      .user-tab-item+.user-tab-item{
        margin-left: 32px;
      }
      .user-tab-active{
        color: #1e6fff;
        font-size: 14px;
        font-weight: 700;
        &::after{
          position: absolute;
          left: 0px;
          content: '';
          bottom: 0px;
          width: 100%;
          height: 3px;
          background: #1E6FFF;
          border-radius: 2px 0px 2px 0px;
        }
      }
    }
    .user-info-body{
      height: 370px;
      .search-box{
        display: flex;
        align-items: center;
        margin: 16px 32px 16px 24px;
        background: #F5F6F7;
        border-radius: 4px 4px 4px 4px;
        .icon{
          width: 16px;
          height: 16px;
          min-width: 16px;
          margin: 0px 12px;
        }
        .close-icon{
          width: 16px;
          height: 16px;
          min-width: 16px;
          cursor: pointer;
          margin: 0px 12px 0 0 ;
        }
        .h-line{
          height: 14px;
          background-color: #d7d8db;
          width: 1px;
          margin-left: 0px;
          margin-right: 0px;
        }
        .el-input{
          .el-input__wrapper{
            background-color: transparent;
            box-shadow: none;
          }
        }
      }
      .content{
        height: 283px;
        .check-box-item{
          margin: 0px 8px;
          height: 36px;
          border-radius: 4px 4px 4px 4px;
          display: flex;
          align-items: center;
          cursor: pointer;
          padding: 0px 16px 0px 24px;
          .icon{
              width: 16px;
              height: 16px;
              min-width: 16px;
              cursor: pointer;
          }
          img{
            width: 24px;
            height: 24px;
            border-radius: 4px 4px 4px 4px;
            margin-left: 12px;
          }
          .name{
            margin-left: 12px;
          }
          &:hover{
            background: #F5F6F7;
          }
        }
        .el-tree{
          margin: 0px 8px;
          .el-tree-node{
            padding-left: 40px !important;
            .el-tree-node__content{
              height: 36px;
              border-radius: 0px 4px 4px 0px;
              &:hover{
                background: #F5F6F7 !important;
                .check-box{
                  background: #F5F6F7 !important;
                }
              }
              .custom-tree-node{
                display: flex;
                align-items: center;
                width: 100%;
                .check-box{
                  position: absolute;
                  left: 0px;
                  padding-left: 20px;
                  display: flex;
                  align-items: center;
                  justify-content: center;
                  width: 44px;
                  height: 36px;
                  border-radius: 4px 0px 0px 4px;
                  .icon{
                    width: 16px;
                    height: 16px;
                    min-width: 16px;
                    cursor: pointer;
                  }
                }
                .tree-labe{
                  width: calc(100% - 40px);
                  text-overflow: ellipsis;
                  overflow: hidden;
                  white-space: nowrap;
                }
              }
            }
            .el-tree-node__children{
              .el-tree-node{
                padding-left: 0px !important;
              }
            }
          }
          .el-tree-node:focus>.el-tree-node__content {
            background-color: transparent;
          }
        }
      }
      .no-user-content{
        height: 323px;
      }
      .page{
        display: flex;
        align-items: center;
        justify-content: end;
        font-size: 14px;
        @include SourceHanSansCN-Regular;
        color: #575e73;
        height: 39px;
        padding-right: 24px;
        border-top: 1px solid #EEEFF0;
        .icon{
            width: 18px;
            min-width: 18px;
            height: 18px;
            cursor: pointer;
        }
        .el-input-number{
            width: 32px;
            height: 20px;
            .el-input-number__decrease,.el-input-number__increase{
                display: none;
            }
            .el-input__wrapper{
                background-color: #F5F6F7 !important;
                box-shadow: none !important;
                padding: 0px 4px !important;
                box-sizing: border-box !important;
            }
        }
        .split{
            padding: 0px 8px 2px;
        }
      }
    }
  }
  .user-info-right{
    width: calc(100% - 460px);
    .user-right-title{
      padding:0px 32px 0px 24px;
      display: flex;
      justify-content: space-between;
      font-size: 14px;
      height: 40px;
      align-items: center;
      .num{
        color: #494F6A;
      }
      .clear{
        color: #1E6FFF;
        cursor: pointer;
      }
    }
    .user-right-content{
      // padding:0px 24px 0px 24px;
      height: 385px;
      .cehck-item{
        display: flex;
        align-items: center;
        justify-content: space-between;
        height: 30px;
        padding:0px 32px 0px 24px;
        .check-item-info{
          text-overflow: ellipsis;
          overflow: hidden;
          white-space: nowrap;
          img{
            width: 24px;
            height: 24px;
            border-radius: 4px 4px 4px 4px;
            margin-right: 12px;
          }
        }
        
        .close-icon{
          width: 14px;
          min-width: 14px;
          height: 14px;
          cursor: pointer;
        }
      }
    }
  }
}
</style>